import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;

// 通过一个类描述一个任务
class MyTimeTask implements Comparable<MyTimeTask>{
    private Runnable runnable;
    private long time;

    MyTimeTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    public int compareTo(MyTimeTask o) {
        return (int) (this.time - o.time);
    }

    public Runnable getRunnable(){
        return runnable;
    }

    public long getTime(){
        return time;
    }
}

// 搞一个定时器的类
class MyTime{
    // 用优先级队列存储任务
    PriorityQueue<MyTimeTask> queue = new PriorityQueue<>();

    Object locker = new Object();

    // 搞一个扫描时间的方法
    public void schedule(Runnable runnable,long delay){
        synchronized (locker) {
            queue.offer(new MyTimeTask(runnable, delay));
            locker.notify();
        }
    }

    public MyTime(){
        Thread t1 = new Thread(()->{
            while(true){
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimeTask task = queue.peek();
                        long time = System.currentTimeMillis();
                        if(time >= task.getTime()){
                            task.getRunnable().run();
                            queue.poll();
                        }else{
                            locker.wait(task.getTime() - time);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
    }
}
public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        MyTime myTime = new MyTime();
        myTime.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("3000!");
            }
        },3000);

        myTime.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("2000!");
            }
        },2000);

        myTime.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("1000!");
            }
        },1000);

        System.out.println("程序启动!");
    }
}

